/**
 * 前端入口
 * tzw 2022年7月5日20:38:47
 */

import React from 'react'
import { Helmet } from 'react-helmet'
import { hydrate, render } from 'react-dom'
import { BrowserRouter, useRoutes } from 'react-router-dom'
// uri => 页面
import loadable, { loadableReady } from '@loadable/component'
import { loadableRouter } from './utils.jsx'
import ErrorBoundary from './ErrorBoundary'
import StoreContext from './context/storeContext'
import store from './store'

const router = {
  '*': loadable(() => import('./page/PageB')),
  '/pagea': loadable(() => import('./page/PageA')),
  '/pageb': loadable(() => import('./page/PageB')),
  '/pageamobx': loadable(() => import('./page/PageAMobx')),
  '/pagebmobx': loadable(() => import('./page/PageBMobx'))
}

function CoreRoutes({ routers }) {
  let element = useRoutes(loadableRouter(routers))

  return element
}

function PageManager() {
  return (
    <React.Fragment>
      <Helmet>
        <meta charSet="utf-8" />
        <title>魅客云</title>
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no, minimal-ui"
        />
        <meta
          name="keywords"
          content="魅客云，魅客云定制，私人定制，个性化定制"
        />
        <meta
          name="description"
          content="魅客云，Maker的音译-魅客，这里是个Maker云集的地方，每个人的工艺品都像天上的云朵，独一无二，也如同独一无二的你。"
        />
        <meta name="full-screen" content="yes" />
        <meta name="x5-fullscreen" content="true" />
        <link
          rel="Shortcut Icon"
          href="http://oscacgbbh.bkt.clouddn.com/ico_16X16.ico"
        />
        <link
          rel="Bookmark"
          href="http://oscacgbbh.bkt.clouddn.com/ico_16X16.ico"
        />
      </Helmet>
      <CoreRoutes routers={router} />
    </React.Fragment>
  )
}

// 这是react官方最新推荐的方式，但是存在问题，在热更新下会报错
// 报错原因们目前来看React.Fragment导致的
// if (typeof document !== 'undefined') {
//   // render方式
//   const create_func = process.env.IS_SSR ? hydrateRoot : createRoot
//   const wrap = create_func(document.getElementById('wrap'))

//   const async = process.env.IS_SSR ? loadableReady : (f) => f()

//   async(() => {
//     wrap.render(
//       <ErrorBoundary>
//         <BrowserRouter>
//           <PageManager />
//         </BrowserRouter>
//       </ErrorBoundary>
//     )
//   })
// }

if (typeof document !== 'undefined') {
  // render方式
  const render_func = process.env.IS_SSR ? hydrate : render
  const async = process.env.IS_SSR ? loadableReady : (f) => f()

  async(() => {
    render_func(
      <ErrorBoundary>
        <StoreContext.Provider value={store}>
          <BrowserRouter>
            <PageManager />
          </BrowserRouter>
        </StoreContext.Provider>
      </ErrorBoundary>,
      document.getElementById('wrap')
    )
  })
}

export default PageManager
